#!/bin/bash

DB_Info=('MySQL 5.6.42' 'MySQL 5.7.24' 'MySQL 8.0.13')

Database_Selection() {
  #which MySQL Version do you want to install?
  if [ -z ${DBSelect} ]; then
    DBSelect="2"
    Echo_Yellow "You have 3 options for your DataBase install."
    echo "1: Install ${DB_Info[0]}"
    echo "2: Install ${DB_Info[1]} (Default)"
    echo "3: Install ${DB_Info[2]}"
    echo "0: DO NOT Install MySQL"
    read -p "Enter your choice (1, 2, 3 or 0): " DBSelect
  fi

  case "${DBSelect}" in
  1)
    echo "You will install ${DB_Info[0]}"
    ;;
  2)
    echo "You will install ${DB_Info[1]}"
    ;;
  3)
    echo "You will Install ${DB_Info[2]}"
    ;;
  0)
    echo "Do not install MySQL!"
    ;;
  *)
    echo "No input,You will install ${DB_Info[1]}"
    DBSelect="2"
    ;;
  esac

  if [[ "${DBSelect}" =~ ^[123]|10$ ]] && [ $(free -m | grep Mem | awk '{print  $2}') -le 1024 ]; then
    echo "Memory less than 1GB, can't install MySQL 5.6+!"
    exit 1
  fi

  MySQL_Bin="/usr/local/mysql/bin/mysql"
  MySQL_Config="/usr/local/mysql/bin/mysql_config"
  MySQL_Dir="/usr/local/mysql"

  if [[ "${DBSelect}" != "0" ]]; then
    #set mysql root password
    if [ -z ${DB_Root_Password} ]; then
      echo "==========================="
      DB_Root_Password="root"
      Echo_Yellow "Please setup root password of MySQL."
      read -p "Please enter: " DB_Root_Password
      if [ "${DB_Root_Password}" = "" ]; then
        echo "NO input,password will be generated randomly."
        DB_Root_Password="yusp#$RANDOM"
      fi
    fi
    echo "MySQL root password: ${DB_Root_Password}"

    #do you want to enable or disable the InnoDB Storage Engine?
    echo "==========================="

    if [ -z ${InstallInnodb} ]; then
      InstallInnodb="y"
      Echo_Yellow "Do you want to enable or disable the InnoDB Storage Engine?"
      read -p "Default enable,Enter your choice [Y/n]: " InstallInnodb
    fi

    case "${InstallInnodb}" in
    [yY][eE][sS] | [yY])
      echo "You will enable the InnoDB Storage Engine"
      InstallInnodb="y"
      ;;
    [nN][oO] | [nN])
      echo "You will disable the InnoDB Storage Engine!"
      InstallInnodb="n"
      ;;
    *)
      echo "No input,The InnoDB Storage Engine will enable."
      InstallInnodb="y"
      ;;
    esac
  fi
}

Dispaly_Selection() {
  Database_Selection
}

Kill_PM() {
  if ps aux | grep "yum" | grep -qv "grep"; then
    if [ -s /usr/bin/killall ]; then
      killall yum
    else
      kill $(pidof yum)
    fi
  elif ps aux | grep "apt-get" | grep -qv "grep"; then
    if [ -s /usr/bin/killall ]; then
      killall apt-get
    else
      kill $(pidof apt-get)
    fi
  fi
}

Press_Install() {
  if [ -z ${YUSP_Auto} ]; then
    echo ""
    Echo_Green "Press any key to install...or Press Ctrl+c to cancel"
    OLDCONFIG=$(stty -g)
    stty -icanon -echo min 1 time 0
    dd count=1 2>/dev/null
    stty ${OLDCONFIG}
  fi
  . include/version.sh
  Kill_PM
}

Press_Start() {
  echo ""
  Echo_Green "Press any key to start...or Press Ctrl+c to cancel"
  OLDCONFIG=$(stty -g)
  stty -icanon -echo min 1 time 0
  dd count=1 2>/dev/null
  stty ${OLDCONFIG}
}

Install_LSB() {
  echo "[+] Installing lsb..."
  if [ "$PM" = "yum" ]; then
    yum -y install redhat-lsb
  elif [ "$PM" = "apt" ]; then
    apt-get update
    apt-get --no-install-recommends install -y lsb-release
  fi
}

Get_Dist_Version() {
  if [ -s /usr/bin/python3 ]; then
    eval ${DISTRO}_Version=$(/usr/bin/python3 -c 'import platform; print(platform.linux_distribution()[1])')
  elif [ -s /usr/bin/python2 ]; then
    eval ${DISTRO}_Version=$(/usr/bin/python2 -c 'import platform; print platform.linux_distribution()[1]')
  fi
  if [ $? -ne 0 ]; then
    Install_LSB
    eval ${DISTRO}_Version=$(lsb_release -rs)
  fi
}

Get_Dist_Name() {
  if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
    DISTRO='CentOS'
    PM='yum'
  elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
    DISTRO='RHEL'
    PM='yum'
  elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
    DISTRO='Aliyun'
    PM='yum'
  elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then
    DISTRO='Fedora'
    PM='yum'
  elif grep -Eqi "Amazon Linux" /etc/issue || grep -Eq "Amazon Linux" /etc/*-release; then
    DISTRO='Amazon'
    PM='yum'
  elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
    DISTRO='Debian'
    PM='apt'
  elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
    DISTRO='Ubuntu'
    PM='apt'
  elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
    DISTRO='Raspbian'
    PM='apt'
  elif grep -Eqi "Deepin" /etc/issue || grep -Eq "Deepin" /etc/*-release; then
    DISTRO='Deepin'
    PM='apt'
  elif grep -Eqi "Mint" /etc/issue || grep -Eq "Mint" /etc/*-release; then
    DISTRO='Mint'
    PM='apt'
  elif grep -Eqi "Kali" /etc/issue || grep -Eq "Kali" /etc/*-release; then
    DISTRO='Kali'
    PM='apt'
  else
    DISTRO='unknow'
  fi
  Get_OS_Bit
}

Get_RHEL_Version() {
  Get_Dist_Name
  if [ "${DISTRO}" = "RHEL" ]; then
    if grep -Eqi "release 5." /etc/redhat-release; then
      echo "Current Version: RHEL Ver 5"
      RHEL_Ver='5'
    elif grep -Eqi "release 6." /etc/redhat-release; then
      echo "Current Version: RHEL Ver 6"
      RHEL_Ver='6'
    elif grep -Eqi "release 7." /etc/redhat-release; then
      echo "Current Version: RHEL Ver 7"
      RHEL_Ver='7'
    fi
  fi
}

Get_OS_Bit() {
  if [[ $(getconf WORD_BIT) == '32' && $(getconf LONG_BIT) == '64' ]]; then
    Is_64bit='y'
  else
    Is_64bit='n'
  fi
}

Get_ARM() {
  if uname -m | grep -Eqi "arm|aarch64"; then
    Is_ARM='y'
  fi
}

Download_Files() {
  local URL=$1
  local FileName=$2
  if [ -s "${FileName}" ]; then
    echo "${FileName} [found]"
  else
    echo "Notice: ${FileName} not found!!!download now..."
    wget -c --progress=bar:force --prefer-family=IPv4 --no-check-certificate ${URL}
  fi
}

Tar_Cd() {
  local FileName=$1
  local DirName=$2
  cd ${cur_dir}/src
  [[ -d "${DirName}" ]] && rm -rf ${DirName}
  echo "Uncompress ${FileName}..."
  tar zxf ${FileName}
  if [ -n "${DirName}" ]; then
    echo "cd ${DirName}..."
    cd ${DirName}
  fi
}

Tarj_Cd() {
  local FileName=$1
  local DirName=$2
  cd ${cur_dir}/src
  [[ -d "${DirName}" ]] && rm -rf ${DirName}
  echo "Uncompress ${FileName}..."
  tar jxf ${FileName}
  if [ -n "${DirName}" ]; then
    echo "cd ${DirName}..."
    cd ${DirName}
  fi
}

Check_YUSPConf() {
  if [ ! -s "${cur_dir}/yusp.conf" ]; then
    Echo_Red "yusp.conf was not exsit!"
    exit 1
  fi
  if [[ "${Download_Mirror}" == "" || "${MySQL_Data_Dir}" == "" || "${Default_Website_Dir}" == "" ]]; then
    Echo_Red "Can't get values from yusp.conf!"
    exit 1
  fi
  if [[ "${MySQL_Data_Dir}" == "/" || "${Default_Website_Dir}" == "/" ]]; then
    Echo_Red "Can't set MySQL/Website Directory to / !"
    exit 1
  fi
}

Print_APP_Ver() {
  echo "You will install ${Stack} stack."
  if [ "${Stack}" != "lamp" ]; then
    echo "${Nginx_Ver}"
  fi

  if [[ "${DBSelect}" =~ ^[123]$ ]]; then
    echo "${Mysql_Ver}"
  elif [ "${DBSelect}" = "0" ]; then
    echo "Do not install MySQL!"
  fi

  #echo "${Php_Ver}" TODO Redis_Ver

  echo "Enable InnoDB: ${InstallInnodb}"
  echo "Print yusp.conf infomation..."
  echo "Download Mirror: ${Download_Mirror}"
  echo "Nginx Additional Modules: ${Nginx_Modules_Options}"

  if [ "${Enable_Nginx_Lua}" = "y" ]; then
    echo "enable Nginx Lua."
  fi
  if [[ "${DBSelect}" =~ ^[123]$ ]]; then
    echo "Database Directory: ${MySQL_Data_Dir}"
  elif [ "${DBSelect}" = "0" ]; then
    echo "Do not install MySQL!"
  fi
  echo "Default Website Directory: ${Default_Website_Dir}"
}

Print_Sys_Info() {
  echo "YUSP Version: ${YUSP_Ver}"
  eval echo "${DISTRO} \${${DISTRO}_Version}"
  cat /etc/issue
  cat /etc/*-release
  uname -a
  MemTotal=$(free -m | grep Mem | awk '{print  $2}')
  echo "Memory is: ${MemTotal} MB "
  df -h
  openssl version
}

StartUp() {
  init_name=$1
  echo "Add ${init_name} service at system startup..."
  if [ "$PM" = "yum" ]; then
    chkconfig --add ${init_name}
    chkconfig ${init_name} on
  elif [ "$PM" = "apt" ]; then
    update-rc.d -f ${init_name} defaults
  fi
}

Remove_StartUp() {
  init_name=$1
  echo "Removing ${init_name} service at system startup..."
  if [ "$PM" = "yum" ]; then
    chkconfig ${init_name} off
    chkconfig --del ${init_name}
  elif [ "$PM" = "apt" ]; then
    update-rc.d -f ${init_name} remove
  fi
}

Check_Mirror() {
  if [ ! -s /usr/bin/curl ]; then
    if [ "$PM" = "yum" ]; then
      yum install -y curl
    elif [ "$PM" = "apt" ]; then
      apt-get update
      apt-get install -y curl
    fi
  fi
  country=$(curl -sSk --connect-timeout 30 -m 60 https://ip.vpser.net/country)
  echo "Server Location: ${country}"
  if [ "${Download_Mirror}" = "https://soft.vpser.net" ]; then
    echo "Try http://soft.vpser.net ..."
    mirror_code=$(curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} http://soft.vpser.net)
    if [[ "${mirror_code}" == "200" || "${mirror_code}" == "302" ]]; then
      echo "http://soft.vpser.net http code: ${mirror_code}"
      ping -c 3 soft.vpser.net
    else
      ping -c 3 soft.vpser.net
      if [ "${country}" = "CN" ]; then
        echo "Try http://soft1.vpser.net ..."
        mirror_code=$(curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} http://soft1.vpser.net)
        if [[ "${mirror_code}" == "200" || "${mirror_code}" == "302" ]]; then
          echo "Change to mirror http://soft1.vpser.net"
          Download_Mirror='http://soft1.vpser.net'
        else
          echo "Try http://soft2.vpser.net ..."
          mirror_code=$(curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} http://soft2.vpser.net)
          if [[ "${mirror_code}" == "200" || "${mirror_code}" == "302" ]]; then
            echo "Change to mirror http://soft2.vpser.net"
            Download_Mirror='http://soft2.vpser.net'
          else
            echo "Can not connect to download mirror,Please modify lnmp.conf manually."
            echo "More info,please visit https://lnmp.org/faq/download-url.html"
            exit 1
          fi
        fi
      else
        echo "Try http://soft2.vpser.net ..."
        mirror_code=$(curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} http://soft2.vpser.net)
        if [[ "${mirror_code}" == "200" || "${mirror_code}" == "302" ]]; then
          echo "Change to mirror http://soft2.vpser.net"
          Download_Mirror='http://soft2.vpser.net'
        else
          echo "Try http://soft1.vpser.net ..."
          mirror_code=$(curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} http://soft1.vpser.net)
          if [[ "${mirror_code}" == "200" || "${mirror_code}" == "302" ]]; then
            echo "Change to mirror http://soft1.vpser.net"
            Download_Mirror='http://soft1.vpser.net'
          else
            echo "Can not connect to download mirror,Please modify yusp.conf manually."
            echo "More info,please visit https://yusp.org/faq/download-url.html"
            exit 1
          fi
        fi
      fi
    fi
  fi
}

Color_Text() {
  echo -e " \e[0;$2m$1\e[0m"
}

Echo_Red() {
  echo $(Color_Text "$1" "31")
}

Echo_Green() {
  echo $(Color_Text "$1" "32")
}

Echo_Yellow() {
  echo $(Color_Text "$1" "33")
}

Echo_Blue() {
  echo $(Color_Text "$1" "34")
}

Echo_Info() {
  echo $(Color_Text "INFOING: ************************************************************" "34")
  echo $(Color_Text "INFOING: $1" "34")
  echo $(Color_Text "INFOING: ************************************************************" "34")
}

Echo_Warn() {
  echo $(Color_Text "WARNING: ************************************************************" "33")
  echo $(Color_Text "WARNING: $1" "33")
  echo $(Color_Text "WARNING: ************************************************************" "33")
}

Echo_Success() {
  echo $(Color_Text "SUCCESS: ************************************************************" "32")
  echo $(Color_Text "SUCCESS: $1" "32")
  echo $(Color_Text "SUCCESS: ************************************************************" "32")
}

Echo_Error() {
  echo $(Color_Text "ERROR: ************************************************************" "31")
  echo $(Color_Text "ERROR: $1" "31")
  echo $(Color_Text "ERROR: ************************************************************" "31")
}

Check_DB() {
  # 查询mysql的进程得到MySQL_Bin
  tmpvar=$(ps -ef | grep 3306 | grep mysql.sock | awk '{print $8}')
  if [ -z $tmpvar ]; then
    Echo_Red "没有找的合适的mysql执行文件，无法执行mysql指令"
    Is_MySQL="None"
    DB_Name="None"
  else
    MySQL_Bin=${tmpvar%/*}/mysql
    Echo_Green "mysql的bin为 $MySQL_Bin"
    Is_MySQL="y"
    DB_Name="mysql"
  fi

  #    if [[ -s /usr/local/mariadb/bin/mysql && -s /usr/local/mariadb/bin/mysqld_safe && -s /etc/my.cnf ]]; then
  #        MySQL_Bin="/usr/local/mariadb/bin/mysql"
  #        MySQL_Config="/usr/local/mariadb/bin/mysql_config"
  #        MySQL_Dir="/usr/local/mariadb"
  #        Is_MySQL="n"
  #        DB_Name="mariadb"
  #    elif [[ -s /usr/local/mysql/bin/mysql && -s /usr/local/mysql/bin/mysqld_safe && -s /etc/my.cnf ]]; then
  #        MySQL_Bin="/usr/local/mysql/bin/mysql"
  #        MySQL_Config="/usr/local/mysql/bin/mysql_config"
  #        MySQL_Dir="/usr/local/mysql"
  #        Is_MySQL="y"
  #        DB_Name="mysql"
  #    elif [[ -s /usr/bin/mysql && -s /usr/bin/mysqld_safe && -s /etc/my.cnf ]]; then
  #    	MySQL_Bin="/usr/bin/mysql"
  #        MySQL_Config="/usr/bin/mysql_config"
  #        MySQL_Dir="/usr/share/mysql"
  #        Is_MySQL="y"
  #        DB_Name="mysql"
  #    else
  #        Is_MySQL="None"
  #        DB_Name="None"
  #    fi
}

Do_Query() {
  echo "$1" >/tmp/.mysql.tmp
  Check_DB
  # TODO fixed --socket是写死的，需要从mysql进程里获取
  ${MySQL_Bin} --defaults-file=~/.my.cnf --socket=/data/3306/mysql.sock </tmp/.mysql.tmp
  return $?
}

Make_TempMycnf() {
  cat >~/.my.cnf <<EOF
[client]
user=root
password='$1'
EOF
  chmod 600 ~/.my.cnf
}

Verify_DB_Password() {
  Check_DB
  status=1
  while [ $status -eq 1 ]; do
    read -s -p "Enter current root password of Database (Password will not shown): " DB_Root_Password
    Make_TempMycnf "${DB_Root_Password}"
    Do_Query ""
    status=$?
  done
  echo "OK, MySQL root password correct."
}

TempMycnf_Clean() {
  if [ -s ~/.my.cnf ]; then
    rm -f ~/.my.cnf
  fi
  if [ -s /tmp/.mysql.tmp ]; then
    rm -f /tmp/.mysql.tmp
  fi
}
